//#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<assert.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>

char commandline[1024];
int lastcode=0;
extern char **environ;

const char *getusername()
{
    return getenv("USER");
}

const char *gethostname()
{
    return getenv("HOSTNAME");
}

const char *getpwd()
{
    return getenv("PWD");
}

int main()
{
    int quit=0,i=0;
    char *argv[32];
    while(!quit){
    	printf("[%s@%s %s]#",getusername(),gethostname(),getpwd());
    	//scanf("%s",commandline);
    	//scnaf只能获取空格截止的字符串
    	char *s=fgets(commandline,sizeof(commandline),stdin);
    	assert(s!=NULL);
    	(void)s;//抵消编译器的报警	
    	commandline[strlen(commandline)-1]='\0';
    	//	
    	if(s) printf("echo : %s\n",commandline);
    	//
    	//commandline -> "ls -a -l -n\0" -> "ls" "-a" "-l" "-n"
    	//现在将命令行分割，放入args  
    	//strtok(char *str,const char *delim); 分割子串 分割符
    	//
	
	argv[i++]=strtok(commandline," ");
	while(argv[i++]=strtok(NULL," "));
    	if(i-1==0) continue;
	
	// 
	//for(int i=0;argv[i];i++) printf("[%d]:%s\n",i,argv[i]);	    
        //
        //命令解析
        pid_t id=fork();
	if(id<0){
	    perror("fork");
	}
	else if(id==0){
	    //子进程执行命令
	    execvp(argv[0],argv);
	    exit(0);
	}
	else{
	    int status=0;
	    pid_t rid = waitpid(id, &status, 0);
            if(rid == id) 
    	    {
            	lastcode = WEXITSTATUS(status);
       	    }
	}
    }
    return 0;
}
